package com.aaa.backsystem.controller;


import com.aaa.backsystem.entity.*;
import com.aaa.backsystem.service.PetrolStationService;
import com.aaa.backsystem.service.StaffService;
import com.aaa.backsystem.service.impl.FileUploadService;
import com.aaa.backsystem.util.MyConstants;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gyc
 * @since 2020-07-23
 */
@Controller
@RequestMapping("/staff")
public class StaffController extends BaseController {

    @Autowired
    private StaffService staffService;

    @Autowired
    private PetrolStationService petrolStationService;

    @Autowired
    private FileUploadService fileUploadService;

    @GetMapping("/toShowStaff")
    public String toShowStaff(){
        return "/staff/staffList.html";
    }

    @GetMapping("/staffList")
    @ResponseBody
    public LayuiTable staffList(Integer page, Integer limit, String searchstaffName, String searchstaffCard){
        //获取登录用户信息
        User user  = (User) SecurityUtils.getSubject().getPrincipal();
        LayuiTable layuiTable = new LayuiTable();
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("status","0");
        if (user.getPetrolStationId()!=null){
            //获取用户所对应的加油站ID
            Integer petrolStationId = user.getPetrolStationId();
            wrapper.eq("petrol_station_id",petrolStationId);
        }
        //添加模糊查询
        if (null !=searchstaffName && !"".equals(searchstaffName)){
            wrapper.like("staff_name",searchstaffName);
        }
        if (null !=searchstaffCard && !"".equals(searchstaffCard)){
            wrapper.like("staff_card",searchstaffCard);
        }

        int staffCount = staffService.selectCount(wrapper);
        //如果表中没有数据，则不进行分页
        if (staffCount>0){
            Page<Staff> pageInfo = new Page(page,limit);
            Page<Staff> staffPage = staffService.selectPage(pageInfo,wrapper);
            List<Staff> staffList = staffPage.getRecords();
            //从分页结果中提取list集合
            layuiTable.setCode(MyConstants.OPERATION_SUCCESS_CODE);
            layuiTable.setMsg(MyConstants.OPERATION_SUCCESS_MESSAGE);
            layuiTable.setData(staffList);
            layuiTable.setCount(staffCount);
        }
        return layuiTable;
    }



    /**
     * 保存部门
     * @param staff
     * @return
     */
    @RequestMapping("/saveStaff")
    @ResponseBody
    public Result saveStaff(Staff staff){
        Result result = new Result();
        //获取登录用户信息
        User user  = (User) SecurityUtils.getSubject().getPrincipal();
        if (user.getPetrolStationId()!=null) {
            //根据登录用户的信息，获取到油站ID，并把它交给staff类
            staff.setPetrolStationId(user.getPetrolStationId());
            //根据PetrolStationId条件查询出加油站的所有信息
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("petrol_station_id", user.getPetrolStationId());
            List<PetrolStation> selectList = petrolStationService.selectList(wrapper);
            //获取PetrolStation表的名称并添加到staff类修改
            String petrolStationName = String.valueOf(selectList.get(0).getPetrolStationName());
            staff.setStaffComp(petrolStationName);
            boolean insert = staffService.insert(staff);
            if(insert){
                return super.success();
            }else{
                return super.error();
            }
        }else {
            result.setCode(MyConstants.OPERATION_FAIL_CODE);
            result.setMsg("您不是加油站法人，不能添加");
            return result;
        }
    }

    /**
     * 更新部门信息（controller中的方法作用1：页面跳转，2：收受参数，返回参数
     * 不建议在controller中加入过多的业务逻辑）
     * @param staff
     * @return
     */
    @RequestMapping("/updateStaff")
    @ResponseBody
    public Result updateStaff(Staff staff) {
        Result result = new Result();
        //获取登录用户信息
        User user  = (User) SecurityUtils.getSubject().getPrincipal();
        if (user.getPetrolStationId()!=null){
            boolean update = staffService.updateById(staff);
            if (update) {
                return super.success();
            } else {
                return super.error();
            }
        }else {
            result.setMsg("您不是加油站法人，不能编辑");
            return result;
        }

    }



    /**
     * 当行删除
     * @param id
     * @return
     */
    @RequestMapping("/deleteStaff")
    @ResponseBody
    public Result deleteStaff(Integer id){
        Result result = new Result();
        //获取登录用户信息
        User user  = (User) SecurityUtils.getSubject().getPrincipal();
        if (user.getPetrolStationId()!=null){
            boolean delete = staffService.deleteById(id);
            if (delete){
                return super.success();
            }else {
                return super.error();
            }
        }else {
            result.setMsg("您不是加油站法人，不能删除");
            return result;
        }

    }

    /**
     * 删除公告
     */
    @RequestMapping("/deleteBatchStaff")
    @ResponseBody
    public Result deleteBatchStaff(@RequestBody List<Staff> staffList){

        Result result = new Result();
        //获取登录用户信息
        User user  = (User) SecurityUtils.getSubject().getPrincipal();
        if (user.getPetrolStationId()!=null){
            List list = new ArrayList();
            for (int i = 0; i <staffList.size() ; i++) {
                list.add(staffList.get(i).getId());
            }
            boolean deleteBatchIds = staffService.deleteBatchIds(list);
            if (deleteBatchIds){
                return super.success();
            }else {
                return super.error();
            }
        }else {
        result.setMsg("您不是加油站法人，不能删除");
        return result;
        }
    }

    //@ResponseBody
    @RequestMapping("/fmtDate")
    @ResponseBody
    public Result fmtDate(String str){
        /**从身份证截取生日信息
         * author:huangjy 2016-07-15    Date转换成String,只需将parse方法换成format方法
         * */
        String Id=str;
        String year = Id.substring(6, 10);//调用substring方法返回相关字段，注意索引从0开始
        String month =Id.substring(10, 12);
        String day = Id.substring(12, 14);
        String birthday = year + "-" + month + "-" + day;

        if(birthday!=null){
           return success(birthday);
        }
        return error();
    }

    /**
     * 文件上传到oss
     */
    @RequestMapping("/uploadPic")
    @ResponseBody
    public FileUploadResult upload(@RequestParam("file") MultipartFile uploadFile) throws Exception {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        FileUploadResult result = new FileUploadResult();
        if(user.getPetrolStationId()!=null){
            result = fileUploadService.upload(uploadFile);
            String url = "https://" + result.getName();
            Staff staff = new Staff();
            staff.setPetrolStationId(user.getPetrolStationId());
            staff.setPic(url);
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("petrol_station_id",user.getPetrolStationId());
            staffService.update(staff,wrapper);
            return result;
        }else{
            result.setResponse(MyConstants.OPERATION_FAIL_MESSAGE);
            return  result;
        }
    }
}

